//
//  ConfigViewController.m
//  ViewPoint
//
//  Created by Demiao Lin on 10/20/08.
//  Copyright 2008 Tsinghua. All rights reserved.
//

#import "ConfigViewController.h"
#import "NewSMTH.h"
#import "Setting.h"

@implementation PostConfigViewController

@synthesize contentView;
@synthesize webView;

- (id)init{
	if( (self=[super init]) != nil ){
	}
	return self;
}

- (void) setStyleId:(NSString*) style_id {
    styleId = style_id;
}

- (void)loadView {
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
    
	CGRect rect = [[UIScreen mainScreen] applicationFrame];
	
	contentView = [[[UIView alloc] initWithFrame:rect] autorelease];
	//contentView.backgroundColor = [UIColor blackColor];
	contentView.autoresizesSubviews = YES;
	contentView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
	contentView.multipleTouchEnabled = YES;
    
    //self.multipleTouchEnabled = YES;
    //self.navigationController.navigationBar.
    
	webView = [[[UIWebView alloc] initWithFrame:CGRectMake(0.0f, 44.0f, 320.0f, 460.0f-44.0f)] autorelease];
	webView.backgroundColor = [UIColor blackColor];
    
    webView.multipleTouchEnabled = YES;
    webView.exclusiveTouch = NO;
    [webView setUserInteractionEnabled:YES];
    
    //webView.scalesPageToFit = YES;
    contentView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
	[contentView addSubview:webView];
	self.view = self.contentView;
	
	[pool release];
}


- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
    //NSString *url = [NSString stringWithFormat:@"http://%@/vp/css/?id=%@", IPSMTH_HOST, styleId];
    NSString *url = [NSString stringWithFormat:@"http://%@/vp/css/?action=list", IPSMTH_HOST];
	//NSLog(url);
	NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:url] 
												cachePolicy:NSURLRequestReturnCacheDataElseLoad
											timeoutInterval:60.0];
	
	[webView loadRequest:theRequest];
	//[webView loadHTMLString:@"<html><body style='background-color: #222;'></body></html>" baseURL:[NSURL URLWithString:@"http://ipsmth.appspot.com/vp/"]];
	
}

- (void)dealloc {
	[webView release];
	[contentView release];
	[super dealloc];
}

@end

@implementation ConfigViewController

//@synthesize tableView;
@synthesize postConfigViewController;

- (id) initWithTitle: (NSString *) title {
	//if( (self = [super init]) != nil ){
	if( (self = [super initWithStyle:UITableViewStyleGrouped]) != nil ){
        self.title = title;
        settings = [[Setting alloc] init];
	}
	return self;
}

- (void)loadView
{	
    [super loadView];
    /*
    CGRect rect = [[UIScreen mainScreen] applicationFrame];
	UIView *mainView = [[UIView alloc] initWithFrame:rect];
	self.view = mainView;
	[mainView release];
    
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
    
    rect.size.height = 44.0f;
    
	UITableView *oneTableView = [[UITableView alloc] initWithFrame:rect
                                                             style:UITableViewStyleGrouped];
	
    UIView *tableHeaderView = [[UIView alloc] initWithFrame:rect];
    UIView *tableFooterView = [[UIView alloc] initWithFrame:rect];
    //tableHeaderView.tag = kHeaderViewTag;
    //tableFooterView.tag = kFooterViewTag;
    oneTableView.tableHeaderView = tableHeaderView;
    oneTableView.tableFooterView = tableFooterView;
    [tableHeaderView release];
    [tableFooterView release];
    
    [oneTableView setEditing:NO animated:YES];
    [oneTableView setAutoresizingMask: (UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth) ];
	[oneTableView setDelegate: self];
    [oneTableView setDataSource: self];
	self.tableView = oneTableView;
	[self.view addSubview:oneTableView];
    [oneTableView release];
    */
	PostConfigViewController *onePostConfigViewController = [[PostConfigViewController alloc] init];
	self.postConfigViewController = onePostConfigViewController;
	[onePostConfigViewController release];
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
    [settings refresh];
    [self setViewsRotation];
}

- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
	//NSLog(@"config viewWillDisappear");
    [self saveSettings];
    [settings persist];
}

- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
	//NSLog(@"config viewDidDisappear");
}

- (UITableViewCell *)tableView:(UITableView *)onetableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *CellIdentifier = [NSString stringWithFormat: @"%d:%d", [indexPath indexAtPosition:0], [indexPath indexAtPosition:1]];
    UITableViewCell *cell = [onetableView dequeueReusableCellWithIdentifier: CellIdentifier];

    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        switch ([ indexPath indexAtPosition: 0]) {
            case(0):
                switch([ indexPath indexAtPosition: 1]) {
                    case(0):
                        nameControl = [[UITextField alloc] initWithFrame:CGRectMake(120, 10, 190, 38)];
                        nameControl.text = (NSString*)[settings valueForKey:knameKey];
                        [nameControl setEnabled:YES];
                        nameControl.placeholder = @"username";
                        nameControl.returnKeyType = UIReturnKeyDone;
                        //nameControl.clearButtonMode = UITextFieldViewModeWhileEditing;
                        nameControl.delegate = self;
                        nameControl.autocapitalizationType=UITextAutocapitalizationTypeNone;
                        
                        [cell addSubview: nameControl];
                        //[nameControl release];
                        
                        cell.text = @"用户名";
                        break;
                    case(1):
                        pwdControl = [[UITextField alloc] initWithFrame:CGRectMake(120, 10, 190, 38)];
                        pwdControl.text = (NSString*)[settings valueForKey:kpwdKey];
                        [pwdControl setEnabled:YES];
                        pwdControl.placeholder = @"password";
                        pwdControl.returnKeyType = UIReturnKeyDone;
                        //pwdControl.clearButtonMode = UITextFieldViewModeWhileEditing;
                        pwdControl.delegate = self;
                        
                        pwdControl.autocapitalizationType = UITextAutocapitalizationTypeNone;
                        pwdControl.secureTextEntry = YES;
                        
                        [cell addSubview: pwdControl];
                        //[pwdControl release];
                        
                        cell.text = @"密码";
                        break;
                    case(2):
                        saveControl = [[UISegmentedControl alloc] initWithFrame: CGRectMake(170, 5, 125, 35)];
                        [saveControl insertSegmentWithTitle: @"是" atIndex: 0 animated: NO];
                        [saveControl insertSegmentWithTitle: @"否" atIndex: 1 animated: NO];
                        if([settings valueForKey:ksave_pwdKey]){
                            saveControl.selectedSegmentIndex = [(NSString*)[settings valueForKey:ksave_pwdKey] intValue];
                        } else {
                            saveControl.selectedSegmentIndex = 1;
                        }
                        
                        [cell addSubview: saveControl];
                        //[saveControl release];
                        
                        cell.text = @"保存";
                        break;
                }
                break;
            case(1):
                switch ([ indexPath indexAtPosition: 1 ]) {
                    case(0):
                        titleControl = [ [ UISwitch alloc ] initWithFrame: CGRectMake(200, 10, 0, 0) ];
                        titleControl.on = [(NSString*)[settings valueForKey:kshow_titleKey] boolValue];
                        [ cell addSubview: titleControl ];
                        //[titleControl release];
                        cell.text = @"显示标题";
                        break;
					case(1):
                        senderControl = [ [ UISwitch alloc ] initWithFrame: CGRectMake(200, 10, 0, 0) ];
                        senderControl.on = [(NSString*)[settings valueForKey:kshow_senderKey] boolValue];
                        [ cell addSubview: senderControl ];
                        //[senderControl release];
                        cell.text = @"显示发信人";
                        break;
                    case(2):
                        dateControl = [ [ UISwitch alloc ] initWithFrame: CGRectMake(200, 10, 0, 0) ];
                        dateControl.on = [(NSString*)[settings valueForKey:kshow_dateKey] boolValue];
                        [ cell addSubview: dateControl ];
                        //[dateControl release];
                        cell.text = @"显示时间";
                        break;
                    case(3):
                        referenceControl = [ [ UISwitch alloc ] initWithFrame: CGRectMake(200, 10, 0, 0) ];
                        referenceControl.on = [(NSString*)[settings valueForKey:kshow_referenceKey] boolValue];
                        [ cell addSubview: referenceControl ];
                        //[referenceControl release];
                        cell.text = @"显示引用文";
                        break;
					case(4):
                        attachmentControl = [ [ UISwitch alloc ] initWithFrame: CGRectMake(200, 10, 0, 0) ];
                        attachmentControl.on = [(NSString*)[settings valueForKey:kshow_attachmentKey] boolValue];
                        [ cell addSubview: attachmentControl ];
                        //[attachmentControl release];
                        cell.text = @"显示附件图片";
                        break;
					case(5):
                        signatureControl = [ [ UISwitch alloc ] initWithFrame: CGRectMake(200, 10, 0, 0) ];
                        signatureControl.on = [(NSString*)[settings valueForKey:kshow_signatureKey] boolValue];
                        [ cell addSubview: signatureControl ];
                        //[signatureControl release];
                        cell.text = @"显示签名档";
                        break;
                }
                break;
            case(2):
                switch ([ indexPath indexAtPosition: 1 ]) {
                    /*
					case(0):
                        textFontControl = [[ UITextField alloc] initWithFrame: CGRectMake(120, 10, 190, 50)];
                        [textFontControl setEnabled: NO];
                        textFontControl.text = (NSString*)[settings valueForKey:ktext_fontKey];
                        [cell addSubview: textFontControl];
                        //[textFontControl release];
                        
                        cell.text = @"正文字体";
                        break;
                    case(1):
                        headFontControl = [[UITextField alloc] initWithFrame: CGRectMake(120, 10, 190, 50)];
                        [headFontControl setEnabled: NO];
                        headFontControl.text = (NSString*)[settings valueForKey:khead_fontKey];
                        [cell addSubview: headFontControl];
                        //[headFontControl release];

                        cell.text = @"其它字体";
                        break;
					*/
                    case(0):
                        styleControl = [[UITextField alloc] initWithFrame: CGRectMake(120, 10, 190, 50)];
                        [styleControl setEnabled: YES];
                        
                        styleControl.placeholder = @"1";
                        styleControl.returnKeyType = UIReturnKeyDone;
                        //styleControl.clearButtonMode = UITextFieldViewModeWhileEditing;
                        styleControl.delegate = self;
                        
                        styleControl.autocapitalizationType = UITextAutocapitalizationTypeNone;
                        //styleControl.secureTextEntry = YES;
                        styleControl.keyboardType = UIKeyboardTypeNumberPad;
                        
                        if([settings valueForKey:kstyleKey]){
                            styleControl.text = (NSString*)[settings valueForKey:kstyleKey];
                        }else{
                            styleControl.text = @"1";
                        }
                        [cell addSubview: styleControl];
                        //[headFontControl release];

                        cell.text = @"样式序号";
                        break;
					case(1):
						cell.text = @"CSS样式";
						cell.selectionStyle = UITableViewCellSelectionStyleBlue;
						cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
				}
                break;
            case(3):
                 switch ([ indexPath indexAtPosition: 1 ]) {
                    case(0):
                        hostControl = [[UITextField alloc] initWithFrame:CGRectMake(120, 10, 190, 38)];
                        hostControl.placeholder = @"Host Only";
                        if([settings valueForKey:khostKey]){
                            hostControl.text = (NSString*)[settings valueForKey:khostKey];
                        }else{
                            hostControl.text = @"ismth.appspot.com";
                        }
                        
                        [hostControl setEnabled:YES];
                        hostControl.returnKeyType = UIReturnKeyDone;
                        //hostControl.clearButtonMode = UITextFieldViewModeWhileEditing;
                        hostControl.delegate = self;
                        hostControl.autocapitalizationType=UITextAutocapitalizationTypeNone;
                        hostControl.keyboardType = UIKeyboardTypeURL;
                        
                        [cell addSubview: hostControl];
                        //[hostControl release];
                        
                        cell.text = @"服务地址";
                        break;
                    case(1):
                        versionControl = [ [ UITextField alloc ] initWithFrame: CGRectMake(120, 10, 190, 38) ];
                        versionControl.text = @"v0.1";
                        [versionControl setEnabled: NO];
                        [cell addSubview: versionControl];
                        //[versionControl release];
                        cell.text = @"Version";
                        break;
                 }
             break;
        }
    }

    return cell;

}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case(0):
            return 3;
            break;
        case(1):
            return 6;
            break;
        case(2):
            return 2;
            break;
        case(3):
            return 2;
            break;
    }

    return 0;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    switch (section) {
        case(0):
            return @"水木帐号";
            break;
        case(1):
            return @"显示设置";
            break;
        case(2):
            return @"样式设置";
            break;
        case(3):
            return @"其他设置";
            break;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	if([indexPath section]==2 && [indexPath row]==1){
        [postConfigViewController setStyleId: styleControl.text];
		[[self navigationController] pushViewController:postConfigViewController animated:YES];
    }
}

- (void) setViewsRotation {
    UIInterfaceOrientation orientation = self.interfaceOrientation;
    if(orientation==UIInterfaceOrientationLandscapeLeft || orientation==UIInterfaceOrientationLandscapeRight){
        //[tableView setFrame:CGRectMake(0.0f, 0.0f, 480.0f, 300.0f)];
        //[tableView.tableHeaderView setFrame:CGRectMake(0.0f, 0.0f, 480.0f, 32.0f)];
	}else{
		//[tableView setFrame:CGRectMake(0.0f, 0.0f, 320.0f, 460.0f)];
        //[tableView.tableHeaderView setFrame:CGRectMake(0.0f, 0.0f, 320.0f, 44.0f)];
	}
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)saveSettings {
    if(saveControl.selectedSegmentIndex==0){
        [settings setValue:nameControl.text forKey:knameKey];
        [settings setValue:pwdControl.text forKey:kpwdKey];
    } else {
        [settings removeObjectForKey:knameKey];
        [settings removeObjectForKey:kpwdKey];
    }
    
    
    [settings setValue:[NSString stringWithFormat:@"%d", saveControl.selectedSegmentIndex] forKey:ksave_pwdKey];
    
    [settings setValue:[NSString stringWithFormat:@"%d", senderControl.on] forKey:kshow_senderKey];
    [settings setValue:[NSString stringWithFormat:@"%d", dateControl.on] forKey:kshow_dateKey];
    [settings setValue:[NSString stringWithFormat:@"%d", ipControl.on] forKey:kshow_ipKey];
	
	[settings setValue:[NSString stringWithFormat:@"%d", titleControl.on] forKey:kshow_titleKey];
	[settings setValue:[NSString stringWithFormat:@"%d", referenceControl.on] forKey:kshow_referenceKey];
	[settings setValue:[NSString stringWithFormat:@"%d", attachmentControl.on] forKey:kshow_attachmentKey];
	[settings setValue:[NSString stringWithFormat:@"%d", signatureControl.on] forKey:kshow_signatureKey];
	
    //[settings setValue:headFontControl.text forKey:khead_fontKey];
    //[settings setValue:textFontControl.text forKey:ktext_fontKey];
    if([[settings valueForKey:kstyleKey] isEqualToString:styleControl.text] == NO){
        [settings setValue:styleControl.text forKey:kstyleKey];
        [settings removeObjectForKey:kcssKey];
    }
    
    [settings setValue:hostControl.text forKey:khostKey];
}

- (void)dealloc {
	[settings release];
    [nameControl release];
    [pwdControl release];
    [saveControl release];
    
    [senderControl release];
    [dateControl release];
    [ipControl release];

	[titleControl release];
    [referenceControl release];
    [attachmentControl release];
	[signatureControl release];
	
    //[headFontControl release];
    //[textFontControl release];
    [styleControl release];
    
    [hostControl release];
    [versionControl release];
    
    //[tableView release];
    [super dealloc];
}

//TextField degelate

// This method catches the Return action
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

@end
